package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.common.wemedia.NewsUpOrDownConstants;
import com.heima.common.wemedia.WemediaConstants;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    GeneratePageService generatePageService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Override
    @GlobalTransactional
    public void publishArticle(Integer newsId) {
        // 1. 查询并检查自媒体文章  wmNews
        WmNews wmNews = getWmNews(newsId);
        // 2. 封装 ApArticle
        ApArticle apArticle = getApArticle(wmNews);
        // 3. 保存或修改 article信息
        saveOrUpdateArticle(apArticle);
        // 4. 保存关联配置和内容信息
        saveConfigAndContent(wmNews, apArticle);
        // 5. TODO 文章页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(), apArticle);
        // 6. 更新 wmNews状态  改为9  并设置articleId
        updateWmNews(newsId, wmNews, apArticle);
        // 7. TODO 通知es索引库添加文章索引
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE, apArticle.getId());
        log.info("文章发布成功，并发送索引库更新通知   文章id: {}", apArticle.getId());
    }

    @Override
    public ResponseResult load(Short type, ArticleHomeDto dto) {
        // 1. 检查参数: (分页  时间  类型  频道)
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            dto.setSize(10);
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if (!type.equals(ArticleConstants.LOADTYPE_LOAD_NEW) && !type.equals(ArticleConstants.LOADTYPE_LOAD_MORE)) {
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        // 2. 调用mapper查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, type);
        // 3.  返还结果   (封面需要拼接访问前缀  )
        for (ApArticle article : articleList) {
            //封面拼接访问前缀,静态页面添加访问前缀
            parseArticle(article);
        }
        return ResponseResult.okResult(articleList);
    }

    @Override
    public ResponseResult<Integer> findChannelIdByArticleId(Long id) {
        return ResponseResult.okResult(getById(id).getChannelId());
    }

    @Override
    public ResponseResult load2(Short loadType, ArticleHomeDto dto, boolean firstPage) {
        if (firstPage) {
            //从redis缓存中查询热点文章数据
            String articleListJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(articleListJson)) {
                List<ApArticle> articleList = JSON.parseArray(articleListJson, ApArticle.class);
                for (ApArticle apArticlet : articleList) {
                    //封面拼接访问前缀,静态页面添加访问前缀
                    parseArticle(apArticlet);
                }
                return ResponseResult.okResult(articleList);
            }
        }
        return load(loadType, dto);
    }

    /**
     * 封面拼接访问前缀,静态页面添加访问前缀
     *
     * @param apArticle
     */
    private void parseArticle(ApArticle apArticle) {
        String images = apArticle.getImages();
        if (StringUtils.isNotBlank(images)) {
            images = Arrays.stream(images.split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.joining(","));
            apArticle.setImages(images);
        }
        // 给静态页路径添加访问前缀
        apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
    }

    /**
     * 修改自媒体文章
     *
     * @param newsId    文章id
     * @param wmNews    自媒体文章
     * @param apArticle
     */
    private void updateWmNews(Integer newsId, WmNews wmNews, ApArticle apArticle) {
        wmNews.setStatus(WemediaConstants.WM_NEWS_PUBLISH_STATUS);
        wmNews.setArticle_id(apArticle.getId());
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()) {
            log.error("文章发布失败 远程调用修改文章接口失败， 不予发布 , 文章id : {} ", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用修改文章接口失败");
        }
    }

    /**
     * 保存关联配置和内容信息
     *
     * @param wmNews
     * @param apArticle
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        // 添加配置信息
        ApArticleConfig articleConfig = ApArticleConfig.builder().articleId(apArticle.getId())
                .isComment(true).isForward(true)
                .isDown(false).isDelete(false).build();
        apArticleConfigMapper.insert(articleConfig);
        // 添加文章详情
        ApArticleContent articleContent = ApArticleContent.builder().content(wmNews.getContent())
                .articleId(apArticle.getId()).build();
        apArticleContentMapper.insert(articleContent);
    }

    /**
     * 保存或修改文章信息
     *
     * @param apArticle
     */
    private void saveOrUpdateArticle(ApArticle apArticle) {
        // 判断wmNews之前是否关联 articleId
        if (apArticle.getId() == null) {
            //新增
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            apArticle.setComment(0);
            apArticle.setViews(0);
            save(apArticle);
        } else {
            //修改文章
            ApArticle article = getById(apArticle.getId());
            if (article == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的文章不存在");
            }
            updateById(apArticle);
            //删除之前关联的配置信息   内容信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId, article.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, article.getId()));
        }
    }

    /**
     * 封装apArticle
     *
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle article = ApArticle.builder().id(wmNews.getArticle_id())
                .flag((byte) 0)
                .layout(wmNews.getType())
                .createdTime(new Date())
                .publishTime(wmNews.getPublishTime()
                ).build();
        BeanUtils.copyProperties(wmNews, article);
        //远程调用adminFeign 查询频道信息
        ResponseResult<AdChannel> result = adminFeign.findOne(wmNews.getChannelId());
        if (!result.checkCode()) {
            log.error("文章发布失败 远程调用查询频道出现异常， 不予发布 , 文章id : {}  频道id : {}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用查询频道出现异常");
        }
        AdChannel channel = result.getData();
        if (channel == null) {
            log.error("文章发布失败 未查询到相关频道信息， 不予发布 , 文章id : {}  频道id : {}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到相关频道信息");
        }
        article.setChannelName(channel.getName());
        //设置作者信息
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (apAuthor == null) {
            log.error("文章发布失败 未查询到相关作者信息， 不予发布 , 文章id : {}  自媒体用户id : {}", wmNews.getId(), wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "根据自媒体用户，查询关联作者信息失败");
        }
        article.setAuthorId(Long.valueOf(apAuthor.getId()));
        article.setAuthorName(apAuthor.getName());
        return article;
    }

    /**
     * 远程调用查询自媒体文章
     *
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        if (!result.checkCode()) {
            log.error("文章发布失败 远程调用自媒体文章接口失败  文章id: {}", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用自媒体文章接口失败");
        }
        WmNews wmNews = result.getData();
        if (wmNews == null) {
            log.error("文章发布失败 未获取到自媒体文章信息  文章id: {}", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到自媒体文章");
        }
        // 判断状态是否为 4 或 8， 如果不是  不处理
        if (wmNews.getStatus() != 4 && wmNews.getStatus() != 8) {
            log.error("文章发布失败 文章状态不为 4 或 8， 不予发布 , 文章id : {}", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "自媒体文章状态错误");
        }
        return wmNews;
    }
}